﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.DirectoryServices;
using System.Threading;

namespace CSP.Package.Controls
{
    public partial class CRMConnectorPackage : UserControl,IInstallationControl
    {
        public CRMConnectorPackage()
        {
            InitializeComponent();
        }

        #region IInstallationControl Members

        private Installer form;
        public Installer GetForm()
        {
            return form;
        }

        public void SetForm(Installer installer)
        {
            form = installer;
        }


        public static void StartWebsite(int site_id)
        {
            string location = "IIS://localhost/W3SVC/" + site_id.ToString();
            DirectoryEntry entry = new DirectoryEntry(location);
            entry.Invoke("start", new object[] { });
            object status = entry.InvokeGet("Status");
            while ((int)status != 2)
            {
                Thread.Sleep(500);
                status = entry.InvokeGet("Status");
            }

            AuthFlags nAuthFlags = (AuthFlags)(entry.Properties[MetabasePropertyNames.AuthFlags][0]);
            nAuthFlags = nAuthFlags | AuthFlags.AuthAnonymous; //Add anonymous
            nAuthFlags = nAuthFlags | AuthFlags.AuthNTLM; //Add Integrated
            entry.Properties[MetabasePropertyNames.AuthFlags][0] = nAuthFlags;

            entry.CommitChanges();
            entry.Close();

            MessageBox.Show(CSP.Package.labels.CSPInstallInfo_SiteCreated, CSP.Package.labels.CSPInstallInfo_Label, MessageBoxButtons.OK, MessageBoxIcon.Information);
        }


        private bool ValidateInput()
        {
                if (txbPort.Text == string.Empty)
                {
                    txbPort.Text = "80";
                }
                try
                {
                    int i = Convert.ToInt32(txbPort.Text);
                    if (i > 65539)
                    {
                        MessageBox.Show(CSP.Package.labels.CspInstallError_PortInteger, CSP.Package.labels.CspInstallError_Title, MessageBoxButtons.OK, MessageBoxIcon.Error);
                        txbPort.Focus();
                        txbPort.Select();
                        return false;
                    }
                }
                catch
                {
                    MessageBox.Show(CSP.Package.labels.CspInstallError_PortInteger, CSP.Package.labels.CspInstallError_Title, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    txbPort.Focus();
                    txbPort.Select();
                    return false;
                }
                return true;

        }


        public bool Next()
        {
            try
            {
                if (ValidateInput())
                {
                    Process proces = new Process();
                    proces.StartInfo.FileName = @"csp.crmconnector.msi";
                    proces.StartInfo.WorkingDirectory = @"CRMConnector";
                    proces.Start();
                    proces.WaitForExit();
                    if (proces.ExitCode != 0)
                    {
                        throw new ApplicationException(CSP.Package.labels.CspInstallError_Unexpected);
                    }

                    return true;
                }
                else
                    return false;
            }
            catch (Exception ex)
            {
                GetForm().ShowException(ex);
                throw ex;
            }
        }

        public void Previous()
        {
        }

        public void Skip()
        {
        }

        #endregion
       
        private void CRMConnectorPackage_Load(object sender, EventArgs e)
        {
            TranslateLiterals();           
        }


        private void TranslateLiterals()
        {
            richTextBox1.Text = CSP.Package.labels.CRMConnectorPackage_Intro;

            groupBox1.Text = CSP.Package.labels.IISWebSite_GroupBox;

            label5.Text = CSP.Package.labels.Port_Label;
            label6.Text = CSP.Package.labels.HostHeader_Label;
            label2.Text = CSP.Package.labels.Description_Label;
            label1.Text = CSP.Package.labels.Path_Label;
            
            btnCreate.Text =CSP.Package.labels.Create_Label;
        }
        private void btnFolder_Click(object sender, EventArgs e)
        {
            if (folderBrowserDialog1.ShowDialog()==DialogResult.OK)
                txbPath.Text = folderBrowserDialog1.SelectedPath;
        }

        private void btnCreate_Click(object sender, EventArgs e)
        {
            //TODO: SimpleCMSServicePrincipalName
            string serverComment = txbDescription.Text;
            string path = txbPath.Text;
            if (txbPath.Text.Length > 0)
            {
              System.IO.Directory.CreateDirectory(path);
              string serverBindings = string.Format(":{0}:{1}", txbPort.Text, txbHostHeader.Text);
              DirectoryEntry w3svc = new DirectoryEntry("IIS://localhost/w3svc");
              object[] newSite = new object[] { serverComment, new object[] { serverBindings }, path };
              object siteId = (object)w3svc.Invoke("CreateNewSite", newSite);
              StartWebsite(Convert.ToInt32(siteId));
            }
        }

    }
}
